import 'package:flutter/material.dart';
import 'package:hx_im_plugin/hx_im_plugin.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_items/hq_chat_image_bubble.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_items/hq_chat_order_bubble.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_items/hq_chat_text_bubble.dart';
import 'package:hx_im_plugin_example/hq_im_ui/pages/chat/hq_chat_items/hq_chat_voice_bubble.dart';
import 'package:hx_im_plugin_example/hq_im_ui/utils/hq_chat_voice_player.dart';
import 'package:hx_im_plugin_example/hq_im_ui/utils/wx_pop_up_menu.dart';
import 'package:hx_im_plugin_example/hq_im_ui/widgets/hq_common_widgets.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

typedef OnErrorMessageTap = Function(EMMessage msg);
typedef OnMessageLongPress = Function(EMMessage msg, String value);
typedef OnMessageTap = Function(EMMessage msg);

class HqChatItem extends StatefulWidget {

  final EMConversation conv;

  final EMMessage msg;

  /// 长按消息bubble
  final OnMessageLongPress longPress;

  /// 点击消息bubble
  final OnMessageTap onTap;

  /// 重发按钮点击
  final OnErrorMessageTap errorBtnOnTap;

  /// 头像按钮点击
  final Function(String eid) avatarOnTap;
  const HqChatItem(
      this.msg,
      EMConversation conversation,
      {
        this.onTap,
        this.longPress,
        this.errorBtnOnTap,
        this.avatarOnTap,
      }) : conv = conversation;

  @override
  _HqChatItemState createState() => _HqChatItemState();
}

class _HqChatItemState extends State<HqChatItem> implements EMMessageStatusListener {

  void initState() {
    super.initState();
    widget.msg.setMessageListener(this);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(context) {
    bool isRecv = widget.msg.direction == EMMessageDirection.RECEIVE;
    return Builder(
      builder: (_) {
        _info() {
          return Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            textDirection: isRecv ? TextDirection.ltr : TextDirection.rtl,
            children: [
              Container(
                height: sWidth(42),
                width: sWidth(42),
                margin: EdgeInsets.only(
                  left: sWidth(isRecv ? 20 : 10),
                  right: sWidth(!isRecv ? 20 : 10),
                ),
                child: _avatarWidget(),
              ),
              _messageWidget(isRecv),
            ],
          );
        }

        Widget ret;
        if (isRecv && widget.msg.chatType != EMMessageChatType.Chat) {
          ret = Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                margin: EdgeInsets.only(
                  left: sWidth(25),
                ),
                child: Text(
                  widget.msg.from, // widget.msg.from,
                  style: TextStyle(
                    fontSize: sFontSize(11),
                    color: Colors.grey,
                  ),
                ),
              ),
              SizedBox(
                height: sHeight(3),
              ),
              _info(),
            ],
          );
        } else {
          ret = _info();
        }
        return ret;
      },
    );
  }

  /// 头像 widget
  _avatarWidget() {
    return FlatButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        if (widget.avatarOnTap != null) {
          widget.avatarOnTap(widget.msg.from);
        }
      },
      child: Image.asset(
        'images/contact_default_avatar.png',
      ),
    );
  }

  /// 消息 widget
  _messageWidget(bool isRecv) {
    List<String> actions = [];
    switch(widget.msg.body.type) {
      case EMMessageBodyType.TXT:
        actions = ['复制', '转发', '删除'];
        break;
      case EMMessageBodyType.IMAGE:
      actions = ['转发', '删除'];
        break;
      case EMMessageBodyType.VOICE:
        actions = ['删除'];
        break;
      case EMMessageBodyType.CUSTOM:
        actions = ['转发', '删除'];
        break;
    }

    return Builder(
      builder: (context) {
        return WPopupMenu(
          onValueChanged: (int value) {
            if(value != null) {
              if (widget.longPress != null) {
                widget.longPress(widget.msg, actions[value]);
              }
            }
          },
          pressType: PressType.longPress,
          actions: actions,
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              if (widget.onTap != null) {
                widget.onTap(widget.msg);
              }
            },
            child: Container(
              constraints: BoxConstraints(
                maxWidth: sWidth(245),
              ),
              margin: EdgeInsets.only(
                top: sHeight(5),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(!isRecv ? 10 : 0),
                  topRight: Radius.circular(isRecv ? 10 : 0),
                  bottomLeft: Radius.circular(10),
                  bottomRight: Radius.circular(10),
                ),
                child: Column(
                  crossAxisAlignment: isRecv ? CrossAxisAlignment.start : CrossAxisAlignment.end,
                  children: [
                    _messageBubble(),
                    _messageStateWidget(isRecv),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 消息状态，
  /// 单聊发送方：消息状态和对方是否已读；
  ///
  /// 群聊发送方：消息状态；
  _messageStateWidget(bool isRecv) {
    // 发出的消息
    if (!isRecv) {
      // 对方已读
      if (widget.msg.hasReadAck) {
        return Container(
          margin: EdgeInsets.only(
            left: sWidth(5),
            right: sWidth(5),
            bottom: sWidth(10),
            top: sWidth(10),
          ),
          alignment: Alignment.bottomRight,
          child: Text(
            '已读',
            style: TextStyle(
              color: Colors.grey,
            ),
          ),
        );
      } else {
        return Builder(
          builder: (_) {
            if (widget.msg.status == EMMessageStatus.PROGRESS) {
              return Padding(
                padding: EdgeInsets.all(sWidth(10)),
                child: SizedBox(
                  width: sWidth(20),
                  height: sWidth(20),
                  child: CircularProgressIndicator(
                    strokeWidth: 1,
                  ),
                ),
              );
            } else if (widget.msg.status == EMMessageStatus.FAIL || widget.msg.status == EMMessageStatus.CREATE) {
              return IconButton(
                padding: EdgeInsets.zero,
                icon: Icon(
                  Icons.error,
                  color: Colors.red,
                  size: sWidth(30),
                ),
                onPressed: () {
                  if (widget.errorBtnOnTap != null) {
                    widget.errorBtnOnTap(widget.msg);
                  }
                },
              );
            }
            return Container();
          },
        );
      }
    }
    return Container();
  }

  @override
  void onDeliveryAck() {}

  @override
  void onError(EMError error) {
    setState(() {});
    print('发送失败');
  }

  @override
  void onProgress(int progress) {
    print('progress --- $progress');
  }

  @override
  void onReadAck() {
    setState(() {});
    print('收到已读回调');
  }

  @override
  void onStatusChanged() {}

  @override
  void onSuccess() {
    setState(() {});
    print('发送成功');
  }

  _messageBubble() {
    EMMessageBody body = widget.msg.body;
    bool isSend = widget.msg.direction != EMMessageDirection.RECEIVE;
    return Builder(builder: (_) {
      Widget bubble;
      switch (body.type) {
        case EMMessageBodyType.TXT:
          bubble = HqChatTextBubble(body);
          break;
        case EMMessageBodyType.LOCATION:
          break;
        case EMMessageBodyType.IMAGE:
          bubble = HqChatImageBubble(body, isSend);
          break;
        case EMMessageBodyType.VOICE:
          bubble = Builder(builder: (context) {
            return Selector(
              selector: (_, HqChatVoicePlayer player) => Tuple2<String, bool>(player.currentMsgId, player.isPlaying),
              builder: (_, data, __) => HqChatVoiceBubble(
                body,
                isSend,
                (data.item1 == widget.msg.msgId) && data.item2,
              ),
            );
          });
          break;
        case EMMessageBodyType.VIDEO:
          break;
        case EMMessageBodyType.FILE:
          break;
        case EMMessageBodyType.CMD:
          break;
        case EMMessageBodyType.CUSTOM:
          bubble = HQChatOrderBubble(body, widget.conv);
          break;
      }
      return Container(
        color: isSend ? Color.fromRGBO(193, 227, 252, 1) : Colors.white,
        child: bubble,
      );
    });
  }

}


/// 消息类型
enum MsgType {
  HQ_TXT, // 文字消息
  HQ_IMAGE, // 图片消息
  HQ_VIDEO, // 视频消息
  HQ_LOCATION, // 位置消息
  HQ_VOICE, // 音频消息
  HQ_FILE, // 文件消息
  HQ_CMD, // CMD消息
  HQ_CUSTOM, // CUSTOM消息
}